<template>
  <div class="app-container h-flex">
    <div v-loading="listLoading" class="tree-box app-container__left">
      <div class="type-title">菜单</div>
      <el-tree
        ref="tree_box"
        :data="menuTreeData"
        node-key="id"
        icon-class="el-icon-arrow-right"
        :expand-on-click-node="false"
        :props="defaultMenuProps"
        @node-click="nodeClick" />
    </div>
    <div ref="tree_box_right" class="h-flex-elastic v-flex overflow-hidden app-container__right">
      <filter-form :form="listQuery" :data="filterData" @deleta="deleteDatas" @search="search" @addForm="addForm" @resizeTable="resizeTable" />
      <div ref="main" class="v-flex-elastic">
        <el-table
          v-if="height>0"
          ref="multipleTable"
          v-loading="listLoading"
          :data="tableData"
          :height="height"
          tooltip-effect="dark"
          @selection-change="handleTagChange">
          <el-table-column
            align="center"
            type="selection"
            width="50" />
          <el-table-column
            label="序号"
            align="center"
            type="index"
            width="50" />
          <el-table-column
            v-if="tableColumnCheckLists[0].ispass"
            prop="empCode"
            align="center"
            show-overflow-tooltip
            label="员工编码" />
          <el-table-column
            v-if="tableColumnCheckLists[1].ispass"
            prop="empName"
            align="center"
            show-overflow-tooltip
            label="员工姓名" />
          <el-table-column
            prop="sex"
            align="center"
            show-overflow-tooltip
            label="性别">
            <template slot-scope="scope">
              <span v-if="scope.row.sex===0">女</span>
              <span v-if="scope.row.sex===1">男</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="deptName"
            align="center"
            show-overflow-tooltip
            label="所属部门" />
          <el-table-column
            prop="duties"
            align="center"
            show-overflow-tooltip
            label="职务" />
          <el-table-column
            prop="school"
            align="center"
            show-overflow-tooltip
            label="毕业院校" />
          <el-table-column
            prop="educationLevel"
            align="center"
            show-overflow-tooltip
            label="文化程度" />
          <el-table-column
            prop="duties"
            align="center"
            show-overflow-tooltip
            label="职称" />
          <el-table-column
            prop="formalStatus"
            align="center"
            show-overflow-tooltip
            label="正式状态" />
          <el-table-column
            prop="phone"
            align="center"
            show-overflow-tooltip
            label="电话" />
          <el-table-column
            prop="dtDec"
            align="center"
            show-overflow-tooltip
            label="入职时间空" />
          <el-table-column
            prop="workTime"
            align="center"
            show-overflow-tooltip
            label="司龄" />
          <el-table-column
            prop="status"
            align="center"
            show-overflow-tooltip
            label="员工状态" />
          <el-table-column
            fixed="right"
            align="center"
            width="120"
            class-name="small-padding fixed-width">
            <template #header>
              操作
              <el-dropdown :hide-on-click="false">
                <i class="el-icon-s-operation columnSetIco" />
                <el-dropdown-menu slot="dropdown">
                  <el-checkbox-group v-model="tableColumnCheck">
                    <el-dropdown-item v-for="(item,index) in checkList" :key="index"><el-checkbox :key="item" :label="item" />
                    </el-dropdown-item>
                  </el-checkbox-group>
                </el-dropdown-menu>
              </el-dropdown>

            </template>
            <template slot-scope="{row ,$index}">
              <el-button
                class="el-icon-defined"
                size="mini"
                icon="el-icon-view"
                @click="view(row)" />
              <el-button
                class="el-icon-defined"
                size="mini"
                icon="el-icon-edit"
                @click="updateForm(row,$index)" />
              <el-button
                class="el-icon-defined"
                size="mini"
                icon="el-icon-delete"
                @click="deleteData(row,$index)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-box">
        <pagination
          :total="total"
          :page.sync="listQuery.page"
          :size.sync="listQuery.size"
          @pagination="getList" />
      </div>
    </div>

    <base-dialog
      class="dictionary-type-dialog"
      :visible.sync="dialog.visible"
      :title="dialog.title"
      :loading="dialog.loading"
      :disabled="dialog.disabled"
      @open="beforeOpenDialog"
      @updateData="updateData">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        :disabled="dialog.disabled"
        label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工编号" prop="empCode">
              <el-input v-model="temp.empCode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="empName">
              <el-input v-model="temp.empName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="民族" prop="nation">
              <el-select v-model="temp.nation">
                <el-option
                  v-for="item in down.nation"
                  :key="item.id"
                  :label="item.dicName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item style="margin-bottom:0;">
              <el-upload
                class="avatar-uploader"
                action="/dfs/upload"
                accept="image/*"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload">
                <img
                  v-if="returnImageUrl"
                  :src="imageUrl"
                  class="avatar"
                  style="max-width: 300px;max-height: 150px;"
                 >
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="temp.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker v-model="temp.birthday" type="date" placeholder="选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idNo">
              <el-input v-model="temp.idNo" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="婚姻状况" prop="marital">
              <el-select v-model="temp.marital">
                <el-option
                  v-for="item in down.marital"
                  :key="item.id"
                  :label="item.dicName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="健康状态" prop="health">
              <el-select v-model="temp.health">
                <el-option
                  v-for="item in down.health"
                  :key="item.id"
                  :label="item.dicName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="所属公司" prop="companyId">
              <select-tree
                ref="tree_box1"
                v-model="temp.companyId"
                node-click
                :options="deptTreeData"
                :props="defaultProps"
                @nodeClick="mentchange" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <select-tree
                ref="tree_box1"
                v-model="temp.deptId"
                node-click
                :options="ethnicList"
                :props="deptIdProps" />
              <!-- <el-select v-model="temp.deptId">
                <el-option
                  v-for="item in ethnicList"
                  :key="item.id"
                  :label="item.dicKey"
                  :value="item.id" />
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" prop="duties">
              <el-input v-model="temp.duties" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="兼职其他部门no" prop="staffName">
              <el-input v-model="temp.staffName" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="temp.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="temp.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司分机号" prop="companyPhone">
              <el-input v-model="temp.companyPhone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司短号" prop="shortPhone">
              <el-input v-model="temp.shortPhone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业院校" prop="school">
              <el-input v-model="temp.school" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="major">
              <el-select v-model="temp.major">
                <el-option
                  v-for="item in down.major"
                  :key="item.id"
                  :label="item.dicName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文化程度" prop="educationLevel">
              <el-select v-model="temp.educationLevel">
                <el-option
                  v-for="item in down.educationLevel"
                  :key="item.id"
                  :label="item.dicName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学位" prop="degree">
              <el-select v-model="temp.degree">
                <el-option
                  v-for="item in down.degree"
                  :key="item.id"
                  :label="item.dicName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称" prop="positionTitle">
              <el-select v-model="temp.positionTitle">
                <el-option
                  v-for="item in down.positionTitle"
                  :key="item.id"
                  :label="item.dicName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="政治面貌" prop="polity">
              <el-select v-model="temp.polity">
                <el-option
                  v-for="item in down.polity"
                  :key="item.id"
                  :label="item.dicName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业时间" prop="graduationTime">
              <el-date-picker v-model="temp.graduationTime" type="date" placeholder="选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职时间" prop="entryTime">
              <el-date-picker v-model="temp.entryTime" type="date" placeholder="选择日期" />

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实习时间" prop="internshipTime">
              <el-date-picker v-model="temp.internshipTime" type="date" placeholder="选择日期" />

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试用时间" prop="tryTime">
              <el-date-picker v-model="temp.tryTime" type="date" placeholder="选择日期" />

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转正时间" prop="realUseTime">
              <el-date-picker v-model="temp.realUseTime" type="date" placeholder="选择日期" />

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="离职时间" prop="levelTime">
              <el-date-picker v-model="temp.levelTime" type="date" placeholder="选择日期" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="钉钉编码" prop="dingDingCode">
              <el-input v-model="temp.dingDingCode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="正式状态" prop="formalStatus">
              <el-select v-model="temp.formalStatus">
                <el-option
                  v-for="item in down.formalStatus"
                  :key="item.id"
                  :label="item.dicName"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否在岗" prop="onDutyFlag">
              <el-radio-group v-model="temp.onDutyFlag">
                <el-radio :label="0">离职</el-radio>
                <el-radio :label="1">在岗</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="memo">
              <el-input v-model="temp.memo" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <power
              ref="site"
              :dept-attr="deptAttr" />
          </el-col> -->
        </el-row>
      </el-form>
    </base-dialog>
    <!-- <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false">
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="!disabled"
          type="primary"
          @click="dialogStatus==='create'?addData():updateData()">
          保存
        </el-button>
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import { upload, dictionary, deptList, companyli } from '@/api/sysm'
import { treeList } from '@/api/dsc/sysm/organization'
import { download } from '@/api/sysm/stration/autograph'
import { getToken } from '@/utils/auth'
import { getList, saveOrUpdate, deleteById, employee } from '@/api/dsc/sysm/organization/staff'
import { tableMixin } from '@/utils/public'
import power from './components/power.vue'
export default {
  name: 'DscType',
  components: {
    power
  },
  mixins: [tableMixin],
  data() {
    return {
      multipleSelection: [],
      returnImageUrl: false,
      imageUrl: '', // 上传图片回显
      ethnicList: [],
      menuTreeData: [], // 菜单树
      deptTreeData: [],
      defaultProps: {
        parent: 'pId', // 父级唯一标识
        value: 'id', // 唯一标识
        label: 'companyName', // 标签显示
        children: 'children' // 子级
      },
      deptIdProps: {
        parent: 'pId', // 父级唯一标识
        value: 'id', // 唯一标识
        label: 'label', // 标签显示
        children: 'children' // 子级
      },
      defaultMenuProps: {
        children: 'children',
        label: 'label'
      },
      down: {},
      height: 0, // table高度
      tableData: [], // 表格数据
      listQuery: {// 搜索条件
        page: 1,
        size: 20
      },
      filterData: {
        keyName: {
          key: 'keyName',
          type: 'input',
          title: '人员名称',
          placeholder: '请输入字典名称'
        },
        duties: {
          key: 'duties',
          type: 'input',
          title: '职务',
          placeholder: '请输入职务'
        },
        educationLevel: {
          key: 'educationLevel',
          type: 'select',
          title: '文化程度',
          options: [],
          props: {
            label: 'dicName',
            value: 'id',
            parent: 'parentId'
          }
        },
        positionTitle: {
          key: 'positionTitle',
          type: 'select',
          title: '职称',
          options: [],
          props: {
            label: 'dicName',
            value: 'id',
            parent: 'parentId'
          }
        },
        formalStatus: {
          key: 'formalStatus',
          type: 'select',
          title: '正式状态',
          options: [],
          props: {
            label: 'dicName',
            value: 'id',
            parent: 'parentId'
          }
        },
        major: {
          key: 'major',
          type: 'select',
          title: '专业',
          options: [],
          props: {
            label: 'dicName',
            value: 'id',
            parent: 'parentId'
          }
        }
      },
      platformOptions: [], // 所属平台option
      total: 0,
      textMap: {
        update: '编辑',
        view: '查看',
        create: '添加'
      },
      dialogFormVisible: false, // 弹窗开关
      dialogStatus: '', // 弹窗类型（添加、查看、编辑）
      dialog: {
        visible: false,
        title: '',
        loading: false,
        disabled: false
      },
      temp: {},
      tempForm: {// 弹窗表单
      },
      rowIndex: null,
      rules: {},
      rulesModel: {
        dtName: [{ required: true, message: '必填', trigger: 'blur' },
          { min: 1, message: '大于1个字符', trigger: 'blur' },
          { max: 20, message: '小于20个字符', trigger: 'blur' }],
        dtCode: [{ required: true, message: '必填', trigger: 'blur' },
          { min: 1, message: '大于1个字符', trigger: 'blur' },
          { max: 20, message: '小于20个字符', trigger: 'blur' }],
        dtDec: [{ max: 255, message: '小于255个字符', trigger: 'blur' }]
      },
      listLoading: false,
      disabled: false, // 是否禁止表单操作
      tableColumnCheck: ['字典名称', '字典内容'],
      checkList: ['字典名称', '字典内容'],
      tableColumnCheckLists: [
        { label: '字典名称', prop: 'dtName', ispass: true },
        { label: '字典内容', prop: 'dtCode', ispass: true }
      ]
    }
  },
  watch: {
    tableColumnCheck(newVal) {
      if (newVal) {
        var arr = this.checkList.filter(i => newVal.indexOf(i) < 0) // 未选中
        this.tableColumnCheckLists.map(i => {
          if (arr.indexOf(i.label) !== -1) {
            i.ispass = false
          } else {
            i.ispass = true
          }
        })
      }
    }
  },
  async created() {
    this.temp = Object.assign({}, this.tempForm)
    await this.getListTree()
    this.getList()
    this.downfun()
  },
  methods: {
    beforeAvatarUpload(file) {
      const param = new FormData()
      param.append('file', file)
      upload(param).then(response => {
        this.temp.fileName = response.data
        this.returnImageUrl = true
        this.imageUrl = this.getUrl(response.data)
      })
      return false
    },
    getUrl(url) {
      return (
        process.env.VUE_APP_BASE_API +
        '/sysm/files/download?fileUrl=' +
        url +
        '&access_token=' +
        getToken()
      )
    },
    mentchange(val, node) {
      deptList({ companyId: node.id }).then(response => {
        this.ethnicList = [response.data]
      })
    },
    downfun() {
      // 公司
      companyli().then(response => {
        this.deptTreeData = response.data
        let companyId = 0
        if (response.data.length > 0) {
          companyId = response.data[0].id
        }
        deptList({ companyId }).then(response => {
          this.ethnicList = [response.data]
        })
      })
      this.treeling()
    },
    treeling() {
      dictionary({ page: 1, size: 99, dicCode: 'Nation' }).then(response => {
        this.down.nation = response.data
      })
      dictionary({ page: 1, size: 99, dicCode: 'Marital' }).then(response => {
        this.down.marital = response.data
      })
      dictionary({ page: 1, size: 99, dicCode: 'Health' }).then(response => {
        this.down.health = response.data
      })
      dictionary({ page: 1, size: 99, dicCode: 'Polity' }).then(response => {
        this.down.polity = response.data
      })
      dictionary({ page: 1, size: 99, dicCode: 'Major' }).then(response => {
        this.down.major = response.data
        this.filterData.major.options = response.data
      })
      dictionary({ page: 1, size: 99, dicCode: 'EducationLevel' }).then(response => {
        this.down.educationLevel = response.data
        this.filterData.educationLevel.options = response.data
      })
      dictionary({ page: 1, size: 99, dicCode: 'Degree' }).then(response => {
        this.down.degree = response.data
      })
      dictionary({ page: 1, size: 99, dicCode: 'PositionTitle' }).then(response => {
        this.down.positionTitle = response.data
        this.filterData.positionTitle.options = response.data
      })
      dictionary({ page: 1, size: 99, dicCode: 'Polity' }).then(response => {
        this.down.polity = response.data
      })
      dictionary({ page: 1, size: 99, dicCode: 'FormalStatus' }).then(response => {
        this.down.formalStatus = response.data
        this.filterData.formalStatus.options = response.data
      })
    },
    // 点击tree节点回调
    nodeClick(data) {
      this.listQuery.deptId = data.id
      if (data.app) {
        this.listQuery.deptId = ''
        this.listQuery.appId = data.id
      } else {
        this.listQuery.deptId = data.id
        this.listQuery.appId = ''
      }
      this.search()
    },
    // 查询菜单树
    getListTree() {
      return treeList({}).then(response => {
        this.menuTreeData.push(response.data)
      })
    },
    // 查询列表
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        for (const i of this.tableData) {
          i.isSystem = !!i.isSystem
          i.isPub = !!i.isPub
          i.status = !!i.status
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0 * 1000)
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 搜索
    search() {
      this.listQuery.page = 1
      this.getList()
    },
    // 添加
    addForm() {
      // this.disabled = false
      this.temp = Object.assign({}, this.tempForm)
      // this.dialogStatus = 'create'
      // this.dialogFormVisible = true

      this.rules = Object.assign({}, this.rulesModel)
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '添加',
        loading: false,
        disabled: false
      })
    },
    // 添加数据
    // addData() {
    //   this.validate().then(() => {
    //     this.saveOrUpdate(this.temp, 1)
    //   })
    // },
    // 查看
    view(row) {
      employee(row.id).then(response => {
        response.data.deptId = response.data.depts[0].deptId
        this.temp = Object.assign({}, response.data)
      })

      // this.disabled = true
      // copy obj
      // this.dialogStatus = 'view'
      this.rules = {}
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '查看',
        loading: false,
        disabled: true
      })
    },
    // 编辑
    updateForm(row, $index) {
      employee(row.id).then(response => {
        response.data.deptId = response.data.depts[0].deptId
        this.temp = Object.assign({}, response.data)
      })
      // this.disabled = false
      this.rowIndex = $index
      // this.temp = Object.assign({}, detaila) // copy obj
      // // this.dialogStatus = 'update'
      this.rules = Object.assign({}, this.rulesModel)
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '编辑',
        loading: false,
        disabled: false
      })
    },
    // 编辑数据
    updateData() {
      this.validate().then(() => {
        this.saveOrUpdate(this.temp)
      })
    },
    site(row) {
      this.deptAttr = {
        deptId: row.id,
        deptName: row.deptName,
        deptCode: row.deptCode,
        idPath: row.idPath,
        parentCode: row.parentCode
      }
      this.$refs.site.dialogFormVisible = true
    },
    // type 1 添加，2 编辑
    saveOrUpdate(params, type) {
      params.depts = []
      params.depts.push({
        deptId: params.deptId
      })
      // params.depts[0].companyId = params.ethnicList
      const param = Object.assign({}, params)
      saveOrUpdate(param).then(response => {
        if (this.dialog.title === '添加') {
          this.tableData.unshift(response.data)
          this.total++
        } else {
          Object.assign(this.tableData[this.rowIndex], response.data)
        }
        this.getList()
        this.notifiySuccess('保存成功!')
        this.dialog.visible = false
      })
    },
    beforeOpenDialog() {
      this.returnImageUrl = false
      this.imageUrl = ''

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 启用、停用,是否系统
    enable(row, $index) {
      this.rowIndex = $index
      this.saveOrUpdate(row, 2)
    },
    // 删除
    deleteData(row, $index) {
      this.confirmBox('确定删除?').then(() => {
        deleteById(row.id).then(response => {
          this.notifiySuccess('删除成功!')
          // this.tableData.splice($index, 1)
          // this.total--
          this.getList()
        })
      }).catch(() => {

      })
    },
    // 批量删除
    handleTagChange(val) {
      this.multipleSelection = val
    },
    deleteDatas() {
      const ids = []
      for (const i of this.multipleSelection) {
        // ids += ',' + i.id
        ids.push(i.id)
      }
      // ids = ids.substring(1)

      if (!ids) {
        Message({
          message: '请至少选择一条数据',
          type: 'error',
          duration: 3 * 1000
        })
        return
      }
      let c = 0
      this.confirmBox('确定删除?').then(() => {
        ids.forEach(item => {
          deleteById(item).then(response => {
            c++
            if (ids.length === c) {
              this.notifiySuccess('删除成功!')
              this.getList()
            }
          })
        })
      }).catch(() => {

      })
    }
  }
}
</script>
